/*
 * @Author: jingfuu@163.com
 * @Date: 2024-11-27 16:52:41
 * @LastEditTime: 2024-12-11 13:49:41
 * @Description: file content
 */
import {
  Body,
  Controller,
  Delete,
  Get,
  Inject,
  Logger,
  Param,
  Post,
  Put,
  Query,
  Res,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import SystemConfigService from '../service/SystemConfigService';
import ConfigQueryParam from '../param/ConfigQueryParam';
import ConfigDto from '../dto/ConfigDto';
import { R } from 'src/common/R';
import PageResult from 'src/common/PageResult';
import { Response } from 'express';
import ServiceException from 'src/common/ServiceException';
import { Constants } from 'src/common/Constants';
import { PreAuthorize } from 'src/common/decorator/PreAuthorizeDecorator';
import { Log } from 'src/common/decorator/LogDecorator';
import BusinessType from 'src/common/enum/BusinessType';

/*
 * @Author: jingfuu@163.com
 * @Date: 2024-11-27 16:52:41
 * @LastEditTime: 2024-11-27 17:04:46
 * @Description: 系统配置接口
 */
@ApiTags('系统配置')
@Controller('system/config')
class ConfigController {
  private readonly logger = new Logger(ConfigController.name);

  @Inject()
  private readonly configService: SystemConfigService;

  /**
   * 分页查询
   */
  @PreAuthorize('system:config:list')
  @ApiOperation({ summary: '分页查询' })
  @Get('/list')
  async list(@Query() param: ConfigQueryParam): Promise<R<ConfigDto>> {
    this.logger.log('query config list start, param:' + JSON.stringify(param));
    const result: PageResult<ConfigDto> = await this.configService.list(param);
    return R.page<ConfigDto>(result);
  }

  @Log({ title: '系统参数管理', businessType: BusinessType.EXPORT })
  @PreAuthorize('system:config:export')
  @ApiOperation({ summary: '导出' })
  @Post('/export')
  async exportRole(@Query() param: ConfigQueryParam, @Res() res: Response) {
    try {
      const buffer = await this.configService.export(param);
      res.set({
        'Content-Type': 'application/vnd.ms-excel',
        'Content-Disposition': 'attachment; filename=config.xlsx',
      });
      res.send(buffer);
    } catch (error) {
      this.logger.error('配置列表导出失败', error.stack);
      throw new ServiceException('配置列表导出失败');
    }
  }

  @Log({ title: '系统参数管理', businessType: BusinessType.DELETE })
  @PreAuthorize('system:config:remove')
  @ApiOperation({ summary: '删除' })
  @Delete('/:id')
  async delete(@Param('id') id: string): Promise<R<any>> {
    if (id.indexOf(',') > -1) {
      for (const item of id.split(',')) {
        await this.configService.delete(Number.parseInt(item));
      }
    } else {
      await this.configService.delete(Number.parseInt(id));
    }
    return R.ok();
  }

  @PreAuthorize('system:config:query')
  @ApiOperation({ summary: '详情' })
  @Get('/:id(\\d+)')
  async getDetail(@Param('id') id: number): Promise<R<ConfigDto>> {
    return R.ok(await this.configService.getById(id));
  }

  @Log({ title: '系统参数管理', businessType: BusinessType.UPDATE })
  @PreAuthorize('system:config:edit')
  @ApiOperation({ summary: '修改' })
  @Put()
  async update(@Body() config: ConfigDto): Promise<R<void>> {
    await this.configService.update(config);
    return R.ok();
  }

  @Log({ title: '系统参数管理', businessType: BusinessType.INSERT })
  @PreAuthorize('system:config:add')
  @ApiOperation({ summary: '新增' })
  @Post()
  async add(@Body() config: ConfigDto): Promise<R<void>> {
    await this.configService.add(config);
    return R.ok();
  }

  @ApiOperation({ summary: '根据配置key获取配置value' })
  @Get('/configKey/:configKey')
  async getConfigValueByConfigKey(@Param('configKey') configKey: string) {
    return {
      code: Constants.SUCCESS,
      msg: await this.configService.getConfigValueByConfigKey(configKey),
    };
  }

  @Log({ title: '系统参数管理', businessType: BusinessType.OTHER })
  @ApiOperation({ summary: '刷新缓存' })
  @Post('/refreshCache')
  async refreshCache() {
    await this.configService.refreshCache();
    return R.ok();
  }
}
export default ConfigController;
